package cn.edu.csmzxy.rk233x.auth_system.service.impl;
import cn.edu.csmzxy.rk233x.auth_system.entity.SysRole;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.edu.csmzxy.rk233x.auth_system.entity.SysUser;
import cn.edu.csmzxy.rk233x.auth_system.mapper.SysUserMapper;
import cn.edu.csmzxy.rk233x.auth_system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.edu.csmzxy.rk233x.auth_system.dto.UserDTO;
import cn.edu.csmzxy.rk233x.auth_system.entity.SysUserRole;
import cn.edu.csmzxy.rk233x.auth_system.exception.BusinessException;
import cn.edu.csmzxy.rk233x.auth_system.mapper.SysUserRoleMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
 * @author wumxing
 * @date 2025/10/15 9:51
 * @description  用户管理服务实现
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    //解决循环依赖，延迟加载
    @Lazy
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public SysUser getByUsername(String username) {
        return sysUserMapper.selectByUsername(username);
    }

    @Override
    public IPage<SysUser> selectUserPage(Page<SysUser> page, String username) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        //默认不显示admin用户
        wrapper.eq(SysUser::getIsDeleted, 0)
                .ne(SysUser::getUsername, "admin")
                .like(username != null, SysUser::getUsername, username)
                .orderByAsc(SysUser::getId);
        return sysUserMapper.selectPage(page, wrapper);
    }

    @Override
    @Transactional
    public void addUser(UserDTO userDTO) {
        // 校验用户名唯一性
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, userDTO.getUsername());
        if (sysUserMapper.exists(wrapper)) {
            throw new BusinessException("用户名已存在");
        }

        // 密码加密
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userDTO, user);
        user.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        sysUserMapper.insert(user);

        // 绑定角色
        if (userDTO.getRoleIds() != null && !userDTO.getRoleIds().isEmpty()) {
            for (Long roleId : userDTO.getRoleIds()) {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(user.getId());
                userRole.setRoleId(roleId);
                userRoleMapper.insert(userRole);
            }
        }
    }

    @Override
    @Transactional
    public void updateUser(Long id, UserDTO userDTO) {
        SysUser user = sysUserMapper.selectById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 校验用户名唯一性（排除当前用户）
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, userDTO.getUsername())
                .ne(SysUser::getId, id);
        if (sysUserMapper.exists(wrapper)) {
            throw new BusinessException("用户名已存在");
        }

        // 更新基本信息
        BeanUtils.copyProperties(userDTO, user);
        sysUserMapper.updateById(user);

        // 更新角色关联（先删后加）
        LambdaQueryWrapper<SysUserRole> roleWrapper = new LambdaQueryWrapper<>();
        roleWrapper.eq(SysUserRole::getUserId, id);
        userRoleMapper.delete(roleWrapper);

        if (userDTO.getRoleIds() != null && !userDTO.getRoleIds().isEmpty()) {
            for (Long roleId : userDTO.getRoleIds()) {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(id);
                userRole.setRoleId(roleId);
                userRoleMapper.insert(userRole);
            }
        }
    }

    @Override
    @Transactional
    public void deleteUser(Long id) {
        if (id == 1) { // 禁止删除超级管理员
            throw new BusinessException("不能删除超级管理员");
        }

        // 检查是否有关联角色
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, id);
        List<SysUserRole> userRoles = userRoleMapper.selectList(wrapper);
        if (!userRoles.isEmpty()) {
            userRoleMapper.delete(wrapper);
        }

        // 逻辑删除用户
        sysUserMapper.deleteById(id);
    }
}